package net.ankao.job.utils;

import net.ankao.job.configuration.EmailConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author LILU
 * @date 2025-01-17 16:22
 */
@Component
public class EmailHelper {

    @Resource
    private EmailConfig emailConfig;

    /**
     *
     * @param to 收件人邮箱地址
     */
    public void send(String to,String subject,String text){
        // 收件人电子邮箱
        // 发件人电子邮箱
        String from = emailConfig.getLoginName();
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.put("mail.smtp.host", emailConfig.getSmtpHost());
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        // 创建会话对象并指定认证方式
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, emailConfig.getAuthCode());
            }
        });
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // 设置 From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // 设置 To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // 设置 Subject: 头部头字段
            message.setSubject(subject);
            // 设置实际邮件消息
            message.setText(text);
            // 发送消息
            Transport.send(message);
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

}
